<?php
declare (strict_types = 1);

namespace thinkless\common;

use app\admin\model\AdminModel;
use think\facade\Cookie;
use Exception;
use security\exception\UnAuthorizationException;
use think\Container;
use think\facade\Config;
use think\facade\Request;
use think\facade\Session;
use think\helper\Str;
use thinkless\patch\ContentView;

/**
 * 控制器基础类
 */
abstract class AdminController extends BaseController {

    protected $middleware = [
        // Session初始化
        \think\middleware\SessionInit::class,
        // 权限校验
        \security\think6\TPAuthenticateMiddleware::class,
    ];

    public function getCurrentUserId() {
        try {
            $cache = Session::get(Config::get('security.session_key'), null);
            $cache = json_decode($cache, true);
            $uid = $cache['id'];
            return $uid;
        } catch (\Throwable $th) {
            Session::delete(Config::get('security.session_key'));
            Cookie::delete(Config::get('security.cookie_key'));
            throw new UnAuthorizationException();
        }
    }

    public function getCurrentUser() {
        $uid = $this->getCurrentUserId();
        $user = (new AdminModel())->field('id, username, mobile, avatar_url')->find($uid);
        return $user;
    }

    public function isPost() {
        return Request::isPost();
    }

    public function isAjax() {
        return Request::isAjax();
    }
    
    /**
     * 插件管理端渲染
     */
    public function view($filename = '', $vars = []) {
        $controller = $this->request->controller();
        if(empty($filename)) $filename = $this->request->action();

        // 继承模板
        $viewpath = root_path() .'app' . DS. 'admin' . DS.  'view' . DS;
        Config::set(['view_path' => $viewpath], 'view');
        $content = '{extend name="template/layout"/}';

        // 主文件
        if (strpos($controller, '.')) {
            $pos        = strrpos($controller, '.');
            $controller = substr($controller, 0, $pos) . '.' . Str::snake(substr($controller, $pos + 1));
        } else {
            $controller = Str::snake($controller);
        }
        $filepath = $this->app->getAppPath() . 'view' . DS . $controller . DS . $filename .'.html';
        if(is_file($filepath)) {
            $content .= file_get_contents($filepath);
        } else {
            if(!empty($vars['table'])) {
                $content .= 
                    '{block name="main"}'.
                    '<div class="content">'.
                        '<simple-table source="{$table}" />'.
                    '</div>'.
                    '{/block}';
            } else {
                throw new Exception("模板文件不存在: ".$filepath);
            }
        }
        $view = Container::getInstance()->invokeClass(ContentView::class, [$content, 200]);
        return $view->isContent(true)->assign($vars)->filter(null);
    }

}
